package com.bytz.modules.cms.auditBatch.service.direct;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bytz.common.constant.CommonConstant;
import com.bytz.common.system.query.MPJLambdaWrapperEx;
import com.bytz.common.system.query.MPJQueryGenerator;
import com.bytz.modules.cms.auditBatch.model.AuditBatchCountModel;
import com.bytz.modules.cms.auditBatch.service.IAdminResellerProductChangeService;
import com.bytz.modules.cms.auditBatch.service.IAuditBatchResellerProductService;
import com.bytz.modules.cms.reseller.entity.ResellerProductChange;
import com.bytz.modules.cms.user.constants.AuditBatchConstants;
import com.bytz.modules.cms.user.entity.AuditBatch;
import com.bytz.modules.cms.user.mapper.AuditBatchMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AuditBatchResellerProductServiceImpl extends ServiceImpl<AuditBatchMapper, AuditBatch> implements IAuditBatchResellerProductService {

    @Autowired
    private IAdminResellerProductChangeService changeService;

    @Override
    public IPage<AuditBatchCountModel> queryPage(Page<AuditBatch> page, AuditBatch auditBatch, Map<String, String[]> parameterMap) throws Exception {

        MPJLambdaWrapperEx<AuditBatch> joinWrapper = MPJQueryGenerator.initQueryWrapper(auditBatch, parameterMap, AuditBatch.class);

        IPage<AuditBatchCountModel> result = baseMapper.selectJoinPage(page, AuditBatchCountModel.class, joinWrapper
                .selectCount(ResellerProductChange::getId, AuditBatchCountModel::getCount)
                .selectAll(AuditBatch.class)
                .groupBy(AuditBatch::getId)
                .leftJoin(ResellerProductChange.class, on -> on
                        .eq(AuditBatch::getId, ResellerProductChange::getAuditBatchId)
                        .eq(AuditBatch::getDelFlag, CommonConstant.DEL_FLAG_0)
                        .eq(ResellerProductChange::getDelFlag, CommonConstant.DEL_FLAG_0)
                )
        );
        result.getRecords().forEach(model -> model.setCanEdit(AuditBatchConstants.Status.CAO_GAO.equals(model.getStatus())));
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AuditBatch storage(AuditBatch auditBatch) {
        auditBatch.setStatus(AuditBatchConstants.Status.CAO_GAO);
        auditBatch.setType(AuditBatchConstants.Type.RESELLER_PRODUCT);
        saveOrUpdate(auditBatch);
        changeService.updateEffectTimeByBatchId(auditBatch.getId(), auditBatch.getEffectTime());
        return auditBatch;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AuditBatch submit(AuditBatch auditBatch) {
        auditBatch.setStatus(AuditBatchConstants.Status.DAI_SHENG_XIAO);
        auditBatch.setType(AuditBatchConstants.Type.RESELLER_PRODUCT);
        saveOrUpdate(auditBatch);
        changeService.updateEffectTimeByBatchId(auditBatch.getId(), auditBatch.getEffectTime());
        return auditBatch;
    }

    @Override
    public void syncChange() {
        List<String> batchIds = getUnSyncedBatchIdByType();
        for (String batchId : batchIds) {
            try {
                changeService.syncChangeByBatchId(batchId);
            } catch (Exception e) {
                log.error("经销商独占产品优惠同步失败, batchId:" + batchId, e);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteBatch(String id) {
        changeService.removeByBatchId(id);
        return removeById(id);
    }

    /**
     * 查找商品变更所有待同步的batch的id
     */
    private List<String> getUnSyncedBatchIdByType() {
        return lambdaQuery()
                .eq(AuditBatch::getType, AuditBatchConstants.Type.RESELLER_PRODUCT)
                .eq(AuditBatch::getStatus, AuditBatchConstants.Status.DAI_SHENG_XIAO)
                .lt(AuditBatch::getEffectTime, LocalDateTime.now().plusDays(1).toLocalDate())
                .list().stream()
                .map(AuditBatch::getId)
                .collect(Collectors.toList());
    }
}
